<template>
	<view class="content">
		<view class="information">
			<view class="informationForm">
				<p class="leftTitle">收货人</p>
				<input v-model="customFormData.receivingName" class="rightInput" type="text" placeholder="请填写收货人" />
			</view>
			<view style="height: 1rpx;background-color:#DDDDDD;"></view>
			<view class="informationForm">
				<p class="leftTitle">手机号</p>
				<input v-model="customFormData.receivingPhoneNumber" class="rightInput" type="number"
					placeholder="请填写手机号" />
			</view>
		</view>

		<view class="information">
			<view class="informationForm">
				<p class="leftTitle">所在地区</p>
				<picker class="rightInput picker" mode="multiSelector" :range="multiArray"
					@change="bindMultiPickerChange" @columnchange="bindMultiPickerColumnChange" :value="multiIndex">
					<view>{{ fullAddress || '请选择所在地区' }}</view>
				</picker>
			</view>
			<view style="height: 1rpx;background-color:#DDDDDD;"></view>
			<view class="informationForm">
				<p class="leftTitle">详细地址</p>
				<input v-model="customFormData.detailedAddress" class="rightInput" type="text" placeholder="请填写详细地址" />
			</view>
		</view>

		<view class="information">
			<view class="informationForm">
				<p class="leftTitle">设为默认地址</p>
				<switch style="margin-top: 10rpx;" :checked="indicatorDots" @change="changeIndicatorDots" />
			</view>
		</view>

		<view class="bottomBox">
			<view class="button" @click="goEditAddress">提交</view>
		</view>
	</view>
</template>
<script>
	import {
		getProvincial,
		getCity,
		getDistrict,
		editAddress,
		getAddressList
	} from '@/api/address.js';

	export default {
		data() {
			return {
				customFormData: {
					receivingName: '',
					receivingPhoneNumber: '',
					region: '',
					detailedAddress: '',
					provinceId: '',
					provinceName: '',
					cityId: '',
					cityName: '',
					districtId: '',
					districtName: '',
					state: '' // 新增字段
				},
				multiArray: [
					[],
					[],
					[]
				],
				multiIndex: [0, 0, 0],
				fullAddress: '',
				fullAddressIds: ['', '', ''],
				provinceMap: {},
				cityMap: {},
				countyMap: {},
				id: null,
				indicatorDots: false
			};
		},
		onLoad(option) {
			this.id = option.id; // 获取传递的 id
			this.getAddressDetails(this.id);
		},
		methods: {
			changeIndicatorDots(e) {
				this.indicatorDots = !this.indicatorDots
				console.log(this.indicatorDots, "this.indicatorDots")
			},
			getAddressDetails(id) {
				getAddressList({
					id
				}).then(res => {
					const address = res.data.records[0];
					this.customFormData = {
						id: address.id,
						receivingName: address.receivingName,
						receivingPhoneNumber: address.receivingPhoneNumber,
						detailedAddress: address.detailedAddress,
						provinceId: address.provinceId,
						provinceName: address.provinceName,
						cityId: address.cityId,
						cityName: address.cityName,
						districtId: address.districtId,
						districtName: address.districtName,
						state: address.state // 初始化 state 字段
					};
					if (this.customFormData.state == 0) {
						this.indicatorDots = false
					} else {
						this.indicatorDots = true
					}
					this.fullAddress = `${address.provinceName}-${address.cityName}-${address.districtName}`;
					this.fullAddressIds = [address.provinceId, address.cityId, address.districtId];
					this.loadProvinces();
				}).catch(error => {
					console.error('Failed to get address details:', error);
				});
			},
			loadProvinces() {
				const params = {
					pageSize: 99,
					pageNumber: 1
				};
				getProvincial(params).then(res => {
					this.multiArray[0] = res.data.records.map(item => item.name);
					this.provinceMap = res.data.records.reduce((map, item) => ({
						...map,
						[item.id]: item.name
					}), {});

					if (this.id && this.customFormData.provinceId) {
						const provinceIndex = this.multiArray[0].indexOf(this.provinceMap[this.customFormData
							.provinceId]);
						this.multiIndex[0] = provinceIndex;
						this.loadCities(provinceIndex);
					} else if (this.multiArray[0].length > 0) {
						this.loadCities(0);
					}
				}).catch(error => {
					console.error('Failed to load provinces:', error);
				});
			},
			loadCities(provinceIndex) {
				const provinceName = this.multiArray[0][provinceIndex];
				const provinceId = this.getProvinceId(provinceName);
				const params = {
					atProvincialLevelId: provinceId,
					pageSize: 99,
					pageNumber: 1
				};
				getCity(params).then(res => {
					this.multiArray[1] = res.data.records.map(item => item.name);
					this.cityMap = res.data.records.reduce((map, item) => ({
						...map,
						[item.id]: item.name
					}), {});

					if (this.id && this.customFormData.cityId) {
						const cityIndex = this.multiArray[1].indexOf(this.cityMap[this.customFormData.cityId]);
						this.multiIndex[1] = cityIndex;
						this.loadCounties(cityIndex);
					} else if (this.multiArray[1].length > 0) {
						this.loadCounties(0);
					}

					this.multiArray[2] = [];
					this.multiIndex = [provinceIndex, this.multiIndex[1], 0];
				}).catch(error => {
					console.error('Failed to load cities:', error);
				});
			},
			loadCounties(cityIndex) {
				const cityName = this.multiArray[1][cityIndex];
				const cityId = this.getCityId(cityName);
				const provinceName = this.multiArray[0][this.multiIndex[0]];
				const provinceId = this.getProvinceId(provinceName);
				const params = {
					cityId: cityId,
					pageSize: 99,
					pageNumber: 1
				};
				getDistrict(params).then(res => {
					this.multiArray[2] = res.data.records.map(item => item.name);
					this.countyMap = res.data.records.reduce((map, item) => ({
						...map,
						[item.id]: item.name
					}), {});

					if (this.id && this.customFormData.districtId) {
						const districtIndex = this.multiArray[2].indexOf(this.countyMap[this.customFormData
							.districtId]);
						this.multiIndex[2] = districtIndex;
					}

					this.multiIndex = [this.multiIndex[0], this.multiIndex[1], this.multiIndex[2]];
				}).catch(error => {
					console.error('Failed to load counties:', error);
				});
			},
			bindMultiPickerColumnChange(e) {
				const col = e.detail.column;
				const value = e.detail.value;
				if (col === 0) {
					this.loadCities(value);
				} else if (col === 1) {
					this.loadCounties(value);
				}
			},
			bindMultiPickerChange(e) {
				const index = e.detail.value;
				const provinceName = this.multiArray[0][index[0]];
				const cityName = this.multiArray[1][index[1]];
				const districtName = this.multiArray[2][index[2]];
				const provinceId = this.getProvinceId(provinceName);
				const cityId = this.getCityId(cityName);
				const districtId = this.getCountyId(districtName);

				// 更新 customFormData 中的字段
				this.customFormData.provinceId = provinceId;
				this.customFormData.provinceName = provinceName;
				this.customFormData.cityId = cityId;
				this.customFormData.cityName = cityName;
				this.customFormData.districtId = districtId;
				this.customFormData.districtName = districtName;
				this.customFormData.region = `${provinceName}-${cityName}-${districtName}`;


				this.fullAddress = `${provinceName}-${cityName}-${districtName}`;
				this.fullAddressIds = [provinceId, cityId, districtId];
			},
			goEditAddress() {
				const params = {
					id: this.customFormData.id,
					receivingName: this.customFormData.receivingName,
					receivingPhoneNumber: this.customFormData.receivingPhoneNumber,
					region: this.customFormData.region,
					detailedAddress: this.customFormData.detailedAddress,
					provinceId: this.customFormData.provinceId,
					provinceName: this.customFormData.provinceName,
					cityId: this.customFormData.cityId,
					cityName: this.customFormData.cityName,
					districtId: this.customFormData.districtId,
					districtName: this.customFormData.districtName,
					state: this.customFormData.state
				};
				if (this.indicatorDots) {
					params.state = 1
				} else {
					params.state = 0
				}
				console.log(params, "params");
				editAddress(params).then(response => {
					uni.showToast({
						title: '修改成功',
						icon: 'success'
					});
					uni.navigateBack({
						delta: 1 // 返回上一级页面
					});
				}).catch(error => {
					uni.showToast({
						title: error.message || '请求失败',
						icon: 'none'
					});
				});
			},
			getProvinceId(provinceName) {
				return Object.keys(this.provinceMap).find(key => this.provinceMap[key] === provinceName);
			},
			getCityId(cityName) {
				return Object.keys(this.cityMap).find(key => this.cityMap[key] === cityName);
			},
			getCountyId(districtName) {
				return Object.keys(this.countyMap).find(key => this.countyMap[key] === districtName);
			}
		}
	};
</script>
<style lang="scss">
	@import '@/uni.scss'; // 导入全局 SCSS 变量文件

	.content {
		min-height: 100vh;
		background-color: #F3F3F3;
		position: relative;
		padding-top: 1rpx;
	}

	.information {
		background: #FFFFFF;
		padding: 0rpx 20rpx;
		position: relative;
		margin: 20rpx;
		border-radius: 16rpx;

		.informationForm {
			height: 80rpx;
			display: flex;
			justify-content: flex-start;
			flex-wrap: nowrap;

			.leftTitle {
				width: 30%;
				font-weight: 500;
				font-size: 26rpx;
				color: #000;
				font-weight: 600;
				line-height: 80rpx;
				text-align: left;
				font-style: normal;
			}

			.rightInput {
				width: 70%;
				height: 80rpx;
				font-weight: 500;
				font-size: 26rpx;
				color: #000;
				line-height: 80rpx;
				text-align: left;
				font-style: normal;
			}
		}
	}

	.picker {
		width: 100%;
		height: 80rpx;
		line-height: 80rpx;
		text-align: left;
	}

	.bottomBox {
		width: 100%;
		height: 120rpx;
		position: fixed;
		bottom: 0;
		z-index: 1000;
		background-color: $uni-bg-color-white; // 使用变量代替硬编码颜色
		display: flex;

		.button {
			width: 80%;
			height: 80rpx;
			line-height: 80rpx;
			text-align: center;
			background-color: $uni-bg-color-orange; // 使用变量代替硬编码颜色
			color: #FFFFFF;
			border-radius: 80rpx;
			margin: 20rpx auto;
		}
	}
</style>